#!/usr/bin/env python3
#
# Report gathering for weathercomp.

import datetime
import json
import logging
import urllib.request

class Report:
    """Struct-like class to clearly define the report format"""
    date_observed = None # datetime.date indicating the reported period. 
                         # "Yesterday" is a little timezone-dependent.
    t_min = -274
    t_max = -274

    def __init__(self, date_observed, t_min, t_max):
        self.date_observed = date_observed
        self.t_min = t_min
        self.t_max = t_max

    def __str__(self):
        ret = """\
Report for: {self.date_observed}
Min T: {self.t_min}
Max T: {self.t_max}
""".format(self=self)
        return ret

class ReportGen:
    """Retrieves reports of yesterday's weather from Weather Underground"""
    _baseurl = 'http://api.wunderground.com/api/{key}/yesterday/q/\
{lat:f},{lon:f}.json'
    apikey = ''

    def __init__(self):
        self.log = logging.getLogger('wu-report')
        with open('apikeys/wunderground.key') as keyfile:
            self.apikey = keyfile.read().strip()

    def generate_url(self, latitude, longitude):
        """Generate a query URL to throw at the website.  Returns the URL."""
        url = self._baseurl.format(
            key=self.apikey, 
            lat=float(latitude), 
            lon=float(longitude))
        self.log.debug('URL: ' + url)
        return url

    def getreport(self, latitude, longitude):
        """Fetch a report for the given location"""
        query = self.generate_url(latitude, longitude)
        with urllib.request.urlopen(query) as f:
            data = json.loads(f.read().decode('utf-8'))
        summary = data['history']['dailysummary'][0]
        datestring = '{year}{mon}{mday}'.format(**summary['date'])
        format = '%Y%m%d'
        date_observed = datetime.datetime.strptime(datestring, format).date()
        t_min = int(summary['mintempm'])
        t_max = int(summary['maxtempm'])
        return Report(date_observed, t_min, t_max)

if __name__ == '__main__':
    r = ReportGen()
    print(r.getreport(51.54999924, 5.11666679))